﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace OnlineEducation.ExternalService
{
    public class SMSSender : ISMSSender
    {
        IOptions<SMSOptions> _smsOptions;

        public SMSSender(IOptions<SMSOptions> smsOptions)
        {
            _smsOptions = smsOptions;
        }
        /// <summary>
        /// 发送商业短信
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="content"></param>
        /// <param name="genre"></param>
        /// <returns></returns>
        public Task<string> SendIdentityCodeAsync(string mobile, string content)
        {

            string uri = _smsOptions.Value.Url;// "API地址";
            var temp = new
            {
                _smsOptions.Value.appid,
                _smsOptions.Value.secret,
                mobile,               //  您发送的手机号已,逗号隔开
                content,              //  【签名】您的发送内容

            };

            return posturiAsync(uri, Newtonsoft.Json.JsonConvert.SerializeObject(temp));


        }

        /// <summary>
        /// 提交发送请求
        /// </summary>
        /// <param name="uri">提交地址</param>
        /// <param name="value">提交的JSON字符串</param>
        /// <returns>API的返回信息</returns>
        private async Task<string> posturiAsync(string uri, string value)
        {
            Encoding encoding = Encoding.UTF8;
            WebClient wc = new WebClient();
            byte[] postData = encoding.GetBytes(value);

            // 得到返回字符流
            byte[] responseData = await wc.UploadDataTaskAsync(uri, "POST", postData);

            // 解码
            return encoding.GetString(responseData);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private string MD5Hash(string input)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.ASCII.GetBytes(input));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }
        }



    }



    //public class returnsms
    //{
    //    public string returnstatus { get; set; }
    //    public string message { get; set; }
    //    public string remainpoint { get; set; }
    //    public string taskID { get; set; }
    //    public string successCounts { get; set; }
    //}

}
